package com.lagou.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;



    public RpcDecoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }

    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        if(clazz != null){
            //获取butebuf中的字节数组
            byte[] data;
            int length = byteBuf.readableBytes();
            if (byteBuf.hasArray()) {
                data = byteBuf.array();
                byteBuf.skipBytes(length);
            } else {
                data = new byte[length];
                byteBuf.readBytes(data);
            }
            //调用反序列化
            Object result = serializer.deserialize(clazz, data);

            //写入反序列化的结果
            out.add(result);
        }
    }
}